//
//  RegisterVC.m
//  IntegralDog
//
//  Created by HanenDev on 16/3/14.
//  Copyright © 2016年 hanen. All rights reserved.
//

#import "RegisterVC.h"
#import "Macro.h"

#define VH(X) [UIView getHeight:X]
#define VW(X) [UIView getWidth:X]

@interface RegisterVC ()<UITextFieldDelegate>

@property (nonatomic, strong) UITextField *phoneFld;
@property (nonatomic, strong) UITextField *checkFld;
@property (nonatomic, strong) UITextField *checkFld2;
@property (nonatomic, strong) UITextField *passFld;
@property (nonatomic, strong) UITextField *passFld2;

@property (nonatomic, strong) UIImageView *checkPic;
@property (nonatomic, strong) NSString    *imgKey;

@property (nonatomic, strong) UIButton    *submitBtn;

@property (nonatomic, strong) UIButton    *getCodeBtn;

@end

@implementation RegisterVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.hidesBackButton = YES;
    self.navigationController.navigationBarHidden = YES;
    
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(18, 28, 12, 22)];
    [leftBtn setImage:[UIImage imageNamed:@"Btn_Nourmal_Jiantou"] forState:UIControlStateNormal];
    [leftBtn setImage:[UIImage imageNamed:@"Btn_Push_Jiantou"] forState:UIControlStateSelected];
    [leftBtn addTarget:self action:@selector(goToBack:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:leftBtn];
//    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
//    self.navigationItem.leftBarButtonItem = item;
    
    //self.navigationItem.title = @"注册";
    //获取图形验证码
    [self getCodeImg];
    
    CGFloat ImageWidth = [UIView getWidth:40];
    CGFloat topSpace = [UIView getHeight:60];
    //顶部图标
    UIImageView * phoneView = [[UIImageView alloc] initWithFrame:CGRectMake( CGRectGetMidX(self.view.frame) - ImageWidth / 2.0f , topSpace, ImageWidth, ImageWidth)];
    phoneView.image = [UIImage imageNamed:@"Btn_Normal_zc"];
    phoneView.layer.cornerRadius = ImageWidth / 2.0;
    phoneView.layer.masksToBounds = YES;
    phoneView.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:phoneView];
    
    //注册账号
    UILabel *registerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0 , CGRectGetMaxY(phoneView.frame) + 5, kScreenWidth, [UIView getHeight:20])];
    registerLabel.text = @"注册账号";
    registerLabel.textColor = fontDarkGrayColor;
    registerLabel.textAlignment = NSTextAlignmentCenter;
    registerLabel.font = [UIFont boldSystemFontOfSize:20.0f];
    [self.view addSubview:registerLabel];

    
    CGFloat startX = [UIView getWidth:20];
    CGFloat imageW = VW(15);
    CGFloat imageH = VH(20);
    //手机号
    UIImageView *phoneImg = [[UIImageView alloc] initWithFrame:CGRectMake(startX,registerLabel.maxY + VH(20), imageW, imageH)];
    phoneImg.image = [UIImage imageNamed:@"Btn_Normal_1"];
    [self.view addSubview:phoneImg];
    
    UILabel *phoneLab = [[UILabel alloc] initWithFrame:CGRectMake(VW(50),registerLabel.maxY + VH(21), VW(80), VH(22))];
    phoneLab.text = @"手机号";
    phoneLab.textColor = fontLightGrayColor;
    phoneLab.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:phoneLab];
    _phoneFld = [[UITextField alloc] initWithFrame:CGRectMake(VW(130),registerLabel.maxY + VH(22), kScreenWidth-VW(150), VH(22))];
    _phoneFld.placeholder = @"请输入手机号";
    _phoneFld.keyboardType = UIKeyboardTypePhonePad;//电话键盘
    [_phoneFld setValue:[UIFont boldSystemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
    [self.view addSubview:_phoneFld];
    UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(startX,phoneLab.maxY + VH(5), kScreenWidth - 2*startX, 1)];
    line.layer.borderWidth = 1;
    line.layer.borderColor = [cellGrayColor CGColor];
    [self.view addSubview:line];
    
    //图形验证
    UIImageView *checkImg = [[UIImageView alloc] initWithFrame:CGRectMake(startX,line.maxY + VH(15), imageW, imageH)];
    checkImg.image = [UIImage imageNamed:@"Btn_Normal_2"];
    [self.view addSubview:checkImg];
    UILabel *checkLab = [[UILabel alloc] initWithFrame:CGRectMake(VW(50),line.maxY + VH(16), VW(80), VH(22))];
    checkLab.text = @"图形验证";
    checkLab.textColor = fontLightGrayColor;
    checkLab.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:checkLab];
    _checkFld = [[UITextField alloc] initWithFrame:CGRectMake(VW(130),line.maxY + VH(17), VW(100), VH(22))];
    _checkFld.placeholder = @"请输入图中字符";
    [_checkFld setValue:[UIFont boldSystemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
    [self.view addSubview:_checkFld];
    
    //    UIView *changeView = [[UIView alloc] initWithFrame:CGRectMake1(320,statusBarHeight+44+20+55, 76, 50)];
    
    UIButton *changeBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    changeBtn.frame = CGRectMake(VW(250),line.maxY - VH(10), VW(50), VH(35));
    [changeBtn addTarget:self action:@selector(getCodeImg) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:changeBtn];
    
    self.checkPic = [[UIImageView alloc] initWithFrame:CGRectMake(VW(236),line.maxY + VH(3), VW(62), VH(28))];
    self.checkPic.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:self.checkPic];
    
    UILabel *changeLab = [[UILabel alloc] initWithFrame:CGRectMake(VW(236),self.checkPic.maxY+ VH(2), VW(62), VH(7))];
    changeLab.text = @"换一张";
    changeLab.textAlignment = NSTextAlignmentCenter;
    changeLab.font = [UIFont systemFontOfSize:11];
    changeLab.textColor = fontLightGrayColor;
    [self.view addSubview:changeLab];
    UILabel *line2 = [[UILabel alloc] initWithFrame:CGRectMake(startX,changeLab.maxY + VH(5), kScreenWidth-VW(40), 1)];
    line2.layer.borderWidth = 1;
    line2.layer.borderColor = [cellGrayColor CGColor];
    [self.view addSubview:line2];
    
    //验证码
    UIImageView *checkImg2 = [[UIImageView alloc] initWithFrame:CGRectMake(startX,line2.maxY + VH(15), imageW, imageH)];
    checkImg2.image = [UIImage imageNamed:@"Btn_Normal_2"];
    [self.view addSubview:checkImg2];
    UILabel *checkLab2 = [[UILabel alloc] initWithFrame:CGRectMake(VW(50),line2.maxY + VH(16), VW(80), VH(22))];
    checkLab2.text = @"验证码";
    checkLab2.textColor = fontLightGrayColor;
    checkLab2.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:checkLab2];
    _checkFld2 = [[UITextField alloc] initWithFrame:CGRectMake(VW(130),line2.maxY + VH(17), VW(100), VH(22))];
    _checkFld2.placeholder = @"请输入验证码";
    [_checkFld2 setValue:[UIFont boldSystemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
    [self.view addSubview:_checkFld2];
    _getCodeBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [_getCodeBtn setTitle:NSLocalizedString(@"获取验证码", nil) forState:UIControlStateNormal];
    [_getCodeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_getCodeBtn.titleLabel setFont:[UIFont systemFontOfSize:11]];
    _getCodeBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    _getCodeBtn.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
    [_getCodeBtn setBackgroundColor:yellowBgColor];
    _getCodeBtn.layer.cornerRadius = 2.0;//圆角
    _getCodeBtn.userInteractionEnabled=NO;//不可点击
    _getCodeBtn.alpha=0.4;//变灰
    _getCodeBtn.frame = CGRectMake(VW(234), line2.maxY + VH(5), VW(64), VH(34));
    [_getCodeBtn addTarget:self action:@selector(getCode) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_getCodeBtn];
    UILabel *line3 = [[UILabel alloc] initWithFrame:CGRectMake(startX,_getCodeBtn.maxY + VH(5), kScreenWidth-VW(40), 1)];
    line3.layer.borderWidth = 1;
    line3.layer.borderColor = [cellGrayColor CGColor];
    [self.view addSubview:line3];
    
    //登录密码
    UIImageView *passImg = [[UIImageView alloc] initWithFrame:CGRectMake(startX,line3.maxY + VH(13), imageW, imageH)];
    passImg.image = [UIImage imageNamed:@"Btn_Normal_3"];
    [self.view addSubview:passImg];
    UILabel *passLab = [[UILabel alloc] initWithFrame:CGRectMake(VW(50),line3.maxY + VH(14), VW(80), VH(22))];
    passLab.text = @"登录密码";
    passLab.textColor = fontLightGrayColor;
    passLab.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:passLab];
    _passFld = [[UITextField alloc] initWithFrame:CGRectMake(VW(130),line3.maxY + VH(15), kScreenWidth-VW(150), VH(22))];
    _passFld.placeholder = @"请输入6~20位密码";
    _passFld.secureTextEntry = YES;//密码
    [_passFld setValue:[UIFont boldSystemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
    [self.view addSubview:_passFld];
    UILabel *line4 = [[UILabel alloc] initWithFrame:CGRectMake(startX,_passFld.maxY + VH(5), kScreenWidth-VW(40), 1)];
    line4.layer.borderWidth = 1;
    line4.layer.borderColor = [cellGrayColor CGColor];
    [self.view addSubview:line4];
    
    //确认密码
    UIImageView *passImg2 = [[UIImageView alloc] initWithFrame:CGRectMake(startX,line4.maxY + VH(13), imageW, imageH)];
    passImg2.image = [UIImage imageNamed:@"Btn_Normal_3"];
    [self.view addSubview:passImg2];
    UILabel *passLab2 = [[UILabel alloc] initWithFrame:CGRectMake(VW(50),line4.maxY + VH(14), VW(80), VH(22))];
    passLab2.text = @"确认密码";
    passLab2.textColor = fontLightGrayColor;
    passLab2.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:passLab2];
    _passFld2 = [[UITextField alloc] initWithFrame:CGRectMake(VW(130),line4.maxY + VH(15), kScreenWidth-VW(150), VH(22))];
    _passFld2.placeholder = @"再次输入密码";
    _passFld2.secureTextEntry = YES;//密码
    _passFld2.returnKeyType =UIReturnKeyGo;//return键
    [_passFld2 setValue:[UIFont boldSystemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
    [self.view addSubview:_passFld2];
    UILabel *line5 = [[UILabel alloc] initWithFrame:CGRectMake(startX,_passFld2.maxY + VH(5) , kScreenWidth-VW(40), 1)];
    line5.layer.borderWidth = 1;
    line5.layer.borderColor = [cellGrayColor CGColor];
    [self.view addSubview:line5];
    
//    _submitBtn = [[UIButton alloc]initWithFrame:CGRectMake(startX, kScreenHeight-120, kScreenWidth-2*startX, 50)];
//    [_submitBtn setImage:[UIImage imageNamed:@"Btn_Normal_zhuce"] forState:UIControlStateNormal];
//    [_submitBtn setImage:[UIImage imageNamed:@"Btn_Push_zhuce"] forState:UIControlStateSelected];
//    [_submitBtn addTarget:self action:@selector(sumitReg) forControlEvents:UIControlEventTouchUpInside];
    _submitBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [_submitBtn setTitle:NSLocalizedString(@"确认提交", nil) forState:UIControlStateNormal];
    [_submitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_submitBtn.titleLabel setFont:[UIFont systemFontOfSize:20]];
    [_submitBtn setBackgroundColor:mainOrangeColor];
    _submitBtn.layer.cornerRadius = 4.0;//圆角
    _submitBtn.frame = CGRectMake(20, kScreenHeight-120, kScreenWidth-40, 50);
//    _submitBtn.userInteractionEnabled=NO;//不可点击
//    _submitBtn.alpha=0.4;//变灰
    [_submitBtn addTarget:self action:@selector(sumitReg) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_submitBtn];
    
    _phoneFld.delegate = self;
    _checkFld.delegate = self;
    _checkFld2.delegate = self;
    _passFld.delegate = self;
    _passFld2.delegate = self;
    
    [_phoneFld addTarget:self action:@selector(textFieldChanged:) forControlEvents:UIControlEventEditingChanged];
    [_checkFld addTarget:self action:@selector(textFieldChanged:) forControlEvents:UIControlEventEditingChanged];
    [_checkFld2 addTarget:self action:@selector(textFieldChanged:) forControlEvents:UIControlEventEditingChanged];
    [_passFld addTarget:self action:@selector(textFieldChanged:) forControlEvents:UIControlEventEditingChanged];
    [_passFld2 addTarget:self action:@selector(textFieldChanged:) forControlEvents:UIControlEventEditingChanged];
   
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardDidHideNotification object:nil];
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    
}


- (void)goToBack:(UIButton *)btn{
    //[self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)getCodeImg{
    
    [DataTool postWithUrl:GET_IMGCODE_URL parameters:nil success:^(id data) {
        NSDictionary *jsonDic = IntegrationJsonParserWithData(data);
        //NSLog(@"%@+++++++++++",jsonDic);
        _imgKey = jsonDic[@"imgKey"];
        NSString *str= jsonDic[@"data"];
        NSData *imageData = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];
        UIImage *image =[[UIImage alloc] initWithData:imageData];
        [self.checkPic setImage:image];
        
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
}
/**
 *  获取验证码
 */
- (void)getCode{
    
    if (_phoneFld.text == nil | [_phoneFld.text length] == 0 | ![JudgeNumber boolenPhone:_phoneFld.text]){
        [self.view makeToast:@"请输入正确的手机号"];
        return;
    }else if (_checkFld.text == nil | [_checkFld.text length] == 0 ){
        [self.view makeToast:@"请输入图形验证码"];
        return;
    }
    NSLog(@"%@ ---",_imgKey);
    NSDictionary *dic = @{@"telphone":_phoneFld.text,@"imgKey":_imgKey,@"code":_checkFld.text};
    [DataTool postWithUrl:GET_PHONECODE_URL parameters:dic success:^(id data) {
        NSDictionary *jsonDic = IntegrationJsonParserWithData(data);
        NSLog(@"%@",jsonDic);
        int code = [jsonDic[@"code"]intValue];
        if(code != 100)//
        {
            NSString * message = jsonDic[@"message"];
            [self.view makeToast:message];
        }else{
            [DateTool startTime:_getCodeBtn];
        }
        
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
}

- (void)sumitReg{
    NSLog(@"sumitReg");
    
//    [self dismissViewControllerAnimated:YES completion:nil];
//    return;
    
    if (_phoneFld.text == nil | [_phoneFld.text length] == 0 ){
        [self.view makeToast:@"请输入手机号"];
        return;
    }else if (![JudgeNumber boolenPhone:_phoneFld.text]){
        [self.view makeToast:@"请输入正确的手机号"];
        return;
    }else if (_checkFld.text == nil | [_checkFld.text length] == 0 ){
        [self.view makeToast:@"请输入图形验证码"];
        return;
    }else if (_checkFld2.text == nil | [_checkFld2.text length] == 0 ){
        [self.view makeToast:@"请输入验证码"];
        return;
    }else if (_passFld.text == nil | [_passFld.text length] == 0 ){
        [self.view makeToast:@"请输入密码"];
        return;
    }else if (_passFld2.text == nil | [_passFld2.text length] == 0 ){
        [self.view makeToast:@"请再次输入密码"];
        return;
    }else if ([_passFld.text length] < 6 | [_passFld2.text length] < 6){
        [self.view makeToast:@"密码不小于6位"];
        return;
    }
    if (![_passFld.text isEqualToString:_passFld2.text]) {
        [self.view makeToast:@"两次密码不一致，请重新输入"];
        return;
    }

    
    NSDictionary *dic = @{@"telphone":_phoneFld.text,@"phoneCode":_checkFld2.text,@"password":_passFld.text,@"repassword":_passFld2.text};
    [DataTool postWithUrl:REGISTER_URL parameters:dic success:^(id data) {
        NSDictionary *jsonDic = IntegrationJsonParserWithData(data);
        int code = [jsonDic[@"code"]intValue];
        
        if(code != 100)//
        {
            NSString * message = jsonDic[@"message"];
            [self.view makeToast:message];
            
        }else{
            
            [self.view makeToast:@"注册成功"];
            [DataTool login:_phoneFld.text withPass:_passFld.text fromView:self];
            
            TabbarController *vc = [[TabbarController alloc]init];
            UIWindow *window = [UIApplication sharedApplication].delegate.window;
            window.rootViewController = vc;
            
            //[self.navigationController popViewControllerAnimated:YES];
        }
        
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
        [self.view makeToast:@"注册失败"];
    }];

    
}

- (void)textFieldChanged:(UITextField *)textField{
    if (textField == _phoneFld) {
        if ([_phoneFld.text length] > 20) {
            _phoneFld.text = [_phoneFld.text substringToIndex:20];
        }
    }
    if (textField == _checkFld) {
        if ([_checkFld.text length] > 10) {
            _checkFld.text = [_checkFld.text substringToIndex:10];
        }
    }
    if (textField == _checkFld2) {
        if ([_checkFld2.text length] > 10) {
            _checkFld2.text = [_checkFld2.text substringToIndex:10];
        }
    }
    if (textField == _passFld) {
        if ([_passFld.text length] > 20) {
            _passFld.text = [_passFld.text substringToIndex:20];
        }
    }
    if (textField == _passFld2) {
        if ([_passFld2.text length] > 20) {
            _passFld2.text = [_passFld2.text substringToIndex:20];
        }
    }
    if(_phoneFld.text != nil & [_phoneFld.text length] !=0 & _checkFld.text != nil & [_checkFld.text length] != 0 ){
        _getCodeBtn.userInteractionEnabled=YES;//可点击
        _getCodeBtn.alpha=1;
    }else{
        _getCodeBtn.userInteractionEnabled=NO;//不可点击
        _getCodeBtn.alpha=0.4;
    }
    if(_phoneFld.text != nil & [_phoneFld.text length] != 0 &  _checkFld.text != nil & [_checkFld.text length] != 0 &  _checkFld2.text != nil & [_checkFld2.text length] != 0  & _passFld.text != nil & [_passFld.text length] != 0 & _passFld2.text != nil & [_passFld2.text length] != 0 ){
//        _submitBtn.userInteractionEnabled=YES;//可点击
//        _submitBtn.alpha=1;
    }else{
//        _submitBtn.userInteractionEnabled=NO;
//        _submitBtn.alpha=0.4;
    }
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
}
- (void)keyboardWillShow:(NSNotification *)notify{
    
    NSDictionary *dic = notify.userInfo;
    CGRect keyFrame = [dic [UIKeyboardFrameEndUserInfoKey]CGRectValue];
    CGFloat diff = ABS(keyFrame.origin.y - _passFld2.maxY);
    CGFloat time = [dic [UIKeyboardAnimationDurationUserInfoKey]doubleValue];
    if (_passFld.maxY > keyFrame.origin.y)  {
        [UIView animateWithDuration:time animations:^{
            CGAffineTransform transform = CGAffineTransformMakeTranslation(0, -diff);
            self.view.transform = transform;
        }];
    }
    
}

- (void)keyboardWillHide:(NSNotification *)notify{
    
    NSDictionary *dic = notify.userInfo;
    
    CGFloat timer = [dic [UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:timer animations:^{
        CGAffineTransform form = CGAffineTransformIdentity;
        self.view.transform = form;
    }];
    
}

//关闭虚拟键盘。
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    if(textField == _passFld2){
        [_phoneFld resignFirstResponder];
        [_checkFld resignFirstResponder];
        [_checkFld2 resignFirstResponder];
        [_passFld resignFirstResponder];
        [_passFld2 resignFirstResponder];
        [self sumitReg];
    }
    return YES;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_phoneFld resignFirstResponder];
    [_checkFld resignFirstResponder];
    [_checkFld2 resignFirstResponder];
    [_passFld resignFirstResponder];
    [_passFld2 resignFirstResponder];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
